<template> 
  <div class="manager-task-container">
    <!-- 搜索和过滤区域 -->
    <div class="search-filter-section">
      <el-form :inline="true" class="filter-form">
        <!-- 项目号搜索 -->
        <el-form-item label="项目号">
          <el-input
              v-model="searchForm.projectId"
              placeholder="请输入项目号"
              prefix-icon="el-icon-search"
              @keyup.enter.native="handleSearch">
          </el-input>
        </el-form-item>
        
        <!-- 项目名称搜索 -->
        <el-form-item label="项目名称">
          <el-input
              v-model="searchForm.projectName"
              placeholder="请输入项目名"
              prefix-icon="el-icon-search"
              @keyup.enter.native="handleSearch">
          </el-input>
        </el-form-item>

        <!-- 按钮组 -->
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button @click="sendTextMesg">发送提醒短信</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="main-table-section">
      <el-card>

        <el-table :data="paginatedTableData" style="width: 100%" :stripe="true" :border="true">
          <el-table-column type="expand">
            <template slot-scope="props">
              <el-table :data="props.row.sonData" style="width: 90%; margin-left:40px" :cell-style="cellStyle">
                <el-table-column
                    v-for="(value, index) in sonColumns"
                    :key="index"
                    :label="value.name"
                    :prop="value.propName">
                </el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button v-if="scope.row.taskStatus == '待审核'" @click="dialogVisible = true; taskTimeSub = scope.row.workHours; taskSub = scope.row">审核</el-button>
                    <el-button v-if="scope.row.taskStatus == '未完成'" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
              
            </template>
          </el-table-column>
          <el-table-column
              v-for="(value, key, index) in parentsCloums"
              :key="index"
              :label="value.name"
              :prop="value.propName">
          </el-table-column>
          <el-table-column
              label="任务数量"
              width="100"
              align="center">
            <template slot-scope="scope">
              <el-tag type="info">
                {{ scope.row.sonData ? scope.row.sonData.length : 0 }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="props">
              <el-button type="text" @click="chartProjectName = props.row.projectName; showChart();">查看产值</el-button>
              <el-button v-if="props.row.projectStatus == '在途'" type="primary" @click="addProjectId=props.row.projectId;addProjectName=props.row.projectName; addVisible=true;handleAddTask()">新增任务</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 添加分页组件 -->
        <div class="pagination-container">
          <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-size="pageSize"
              :total="filteredTableData.length"
              layout="total, prev, pager, next">
          </el-pagination>
        </div>
      </el-card>
    </div>

    <!-- 保持原有的对话框不变 -->
    <el-dialog
        title="审核工时"
        :visible.sync="dialogVisible"
        width="40%" center>
        <el-form  label-width="80px">
            <el-form-item label="任务："  label-width="formLabelWidth">
              <span>{{ taskSub.taskName }}</span>
            </el-form-item>
            <el-form-item label="任务负责人："  label-width="formLabelWidth">
              <span>{{ taskSub.memberName }}</span>
            </el-form-item>
            <el-form-item label="工时："  label-width="formLabelWidth">
              <span>{{ taskSub.workHours }}</span>
            </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="handleEdit(); dialogVisible = false">通过</el-button>
          <el-button @click="innerVisible = true; taskTimeChange=''">不通过</el-button>
        </span>
        <el-dialog
            width="30%"
            title="修改工时"
            :visible.sync="innerVisible"
            append-to-body center>
            <el-form  label-width="80px">
                  <el-form-item label="原工时：" label-width="formLabelWidth">
                    <span>{{ taskSub.workHours }}</span>
                  </el-form-item>
                  <el-form-item label="工时："  label-width="formLabelWidth">
                      <el-input v-model="taskTimeChange"></el-input>
                  </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
              <el-button type="primary" @click="taskTimeSub=taskTimeChange; handleEdit(); dialogVisible = false; innerVisible=false">确认</el-button>
              <el-button @click="innerVisible = false">取消</el-button>
            </span>

        </el-dialog>
    </el-dialog>
    <el-dialog
            width="30%"
            title="新增任务"
            :visible.sync="addVisible"
            append-to-body center>
            <h4>项目名： {{ addProjectName }}</h4>
            <el-form  label-width="80px">
              <el-form-item label="新增任务名："  label-width="formLabelWidth">
                  <el-input v-model="taskName" placeholder="任务名"></el-input>
                </el-form-item>
                <el-form-item label="任务权重："  label-width="formLabelWidth">
                  <el-input v-model="taskPercentage" placeholder="任务权重"></el-input>
                </el-form-item>
                <el-form-item label="任务负责人："  label-width="formLabelWidth">
                  <el-select v-model="assignedToId" placeholder="选择选择负责人">
                    <el-option
                        v-for="member in allMembers"
                        :key="member.memberId"
                        :label="member.memberName + ' - ' + member.memberJob"
                        :value="member.memberId">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="开始日期："  label-width="formLabelWidth">
                  <el-date-picker v-model="startDate" type="date" placeholder="开始日期"></el-date-picker>
                </el-form-item>
                <el-form-item label="预计结束日期："  label-width="formLabelWidth">
                  <el-date-picker v-model="endDate" type="date" placeholder="结束日期"></el-date-picker>
                </el-form-item>
              </el-form>

            <span slot="footer" class="dialog-footer">
              <el-button type="primary" @click="addVisible=false;handleConfirmAddTask()">确认新增</el-button>
              <el-button @click="addVisible = false">取消</el-button>
            </span>

    </el-dialog>
    <el-dialog
            width="70%"
            title="项目产值跟踪"
            :visible.sync="chartVisible"
            append-to-body center>
            <div ref="chart" style="height: 400px; "></div>

            <span slot="footer" class="dialog-footer">
              <el-button type="primary" @click="chartVisible=false">确认</el-button>
              <el-button @click="chartVisible = false">取消</el-button>
            </span>

    </el-dialog>
  </div>
</template>

<script>
import http from "@/api/http";
import * as echarts from 'echarts'; // 引入 ECharts
import { getLineChartData } from '@/api'; // 引入获取堆叠折线图数据的接口
import axios from "axios";

export default {
  name: "ManagerTask",
  data() {
    return {
      searchForm: {
        projectId: '',
        projectName: ''
      },
      currentPage: 1,
      pageSize: 15,  // 每页显示15条数据
      taskName: '',
      taskPercentage: '',
      assignedToId: '',
      startDate: '',
      endDate: '',
      userName:'',

      taskSub:'',
      taskTimeSub:'',
      taskTimeChange:'',

      addProjectId:'',
      addProjectName:'',
      allMembers:[],

      chartProjectName:'',
      chart: null,
      chartData: {}, // 存储后端数据
      tooltipData: [], // 鼠标悬停时显示的额外信息
      chartVisible: false,

      dialogVisible: false,
      innerVisible: false,
      addVisible: false,
      
      parentsCloums: [ //外层table的表头
        {
          name: "项目号",
          id: "1",
          propName: "projectId",
        }, {
          name: "项目名称",
          id: "2",
          propName: "projectName",
        }, {
          name: "项目状态",
          id: "3",
          propName: "projectStatus",
        }
      ],
      tableData: [], //外层table的数据
      sonColumns: [ //内层table的表头
        {
          name: "任务名",
          id: "1",
          propName: "taskName",
        },
        {
          name: "任务负责人",
          id: "2",
          propName: "memberName",
        },
        {
          name: "任务权重",
          id: "3",
          propName: "taskPercentage",
        },
        {
          name: "任务工时",
          id: "4",
          propName: "workHours",
        },
        {
          name: "任务状态",
          id: "5",
          propName: "taskStatus",
        }
      ]
    }
  },
  computed: {
    filteredTableData() {
      return this.tableData.filter(item => {
        const idMatch = !this.searchForm.projectId || 
          item.projectId.toString().includes(this.searchForm.projectId);
        
        const nameMatch = !this.searchForm.projectName || 
          item.projectName.toLowerCase().includes(this.searchForm.projectName.toLowerCase());
        
        return idMatch && nameMatch;
      });
    },
    paginatedTableData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.filteredTableData.slice(start, end);
    }
  },
  methods: {
    handleSearch() {
      // 搜索时重置页码
      this.currentPage = 1;
    },
    resetSearch() {
      this.searchForm = {
        projectId: '',
        projectName: ''
      };
      this.currentPage = 1;
      this.fetchProjectsAndTask();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
    },
    handleEdit() {
      // 提交的逻辑
      http.put(`/api/tasks/update/${this.taskSub.taskId}`, null, {
        params: {
          workHours: this.taskTimeSub,
        }})
          .then(res => {
            this.$message.success("任务更新成功");
            this.fetchProjectsAndTask(); // 更新项目和任务列表
          })
          .catch(error => {
            if (error.response && error.response.status === 400) {
              this.$message.error("您没有权限提交该任务");
            } else {
              console.error(`Error updating task ${this.taskSub.taskId}:`, error);
              this.$message.error("任务更新失败");
            }
          });
    },

    handleDelete(index, row) {
      // 删除的逻辑
      http.delete(`/api/tasks/remove/${row.taskId}`)
          .then(res => {
            this.$message.success("任务删除成功");
            this.fetchProjectsAndTask(); // 更新项目和任务列表
          })
          .catch(error => {
            console.error(`Error deleting task ${row.taskId}:`, error);
            this.$message.error("任务删除失败");
          });
    },
    handleAddTask() {
      // 新增任务的逻辑
      http.get(`/api/members/${this.addProjectId}/members`)
          .then(res => {
            const members = res;
            this.allMembers= members;
            
            this.taskName = '';
            this.taskPercentage = '';
            this.assignedToId = '';
            this.startDate = '';
            this.endDate = '';
          })
          .catch(error => {
            console.error(`Error fetching members for project ${this.addProjectId}:`, error);
          });
    },
    handleConfirmAddTask() {
      // 确认新增任务的逻辑
      const payload = {
        taskName: this.taskName,
        projectId: this.addProjectId,
        assignedToId: this.assignedToId,
        taskPercentage: this.taskPercentage,
        startDate: this.startDate,
        endDate: this.endDate
      };
      http.post(`/api/tasks/add`, payload)
          .then(res => {
            this.$message.success("任务新增成功");
            this.addVisible=false;
            this.fetchProjectsAndTask(); // 更新项目和任务列表
          })
          .catch(error => {
            console.error("Error adding new task:", error);
            this.$message.error("任务新增失败");
          });
    },
    async fetchProjectsAndTask() {
      try {
        // 获取所有项目的数据
        const projectsResponse = await http.get('/api/tasks/projects');
        const projects = projectsResponse;

        // 使用 Promise.all 并行获取所有项目的任务信息
        const projectsWithTasks = await Promise.all(projects.map(async (project) => {
          try {
            const tasksResponse = await http.get(`/api/tasks/project/${project.projectId}/tasks`);
            const tasks = tasksResponse || [];
            return {
              ...project,
              sonData: tasks,
              showNewTask: false
            };
          } catch (error) {
            console.error(`Error fetching tasks for project ${project.projectId}:`, error);
            return {
              ...project,
              sonData: [],
              showNewTask: false
            };
          }
        }));
        this.tableData = projectsWithTasks;
      } catch (error) {
        console.error('Error fetching projects:', error);
      }
    },
    
    getName(){
      http.get('/api/userinfo')
          .then(res=>{
            this.userName=res.userName;
            console.log('getUSER',this.userName)
            console.log('getUSER',res.userName);
          })
          .catch(error=>{
            console.error('获取用户名失败');
            this.$message.error("获取用户名失败");
          })
    },
    cellStyle(){//根据情况显示背景色
      return 'background:#F3F6FF'
    },
    showChart(){
      this.chartVisible = true;
      // 等待 DOM 渲染完成后初始化图表
      this.$nextTick(() => {
        this.initChart(); // 初始化图表
        this.fetchChartData(this.chartProjectName); // 获取图表数据
      });
    },
    initChart() {
      const chartDom = this.$refs.chart;
      console.log('图表容器 DOM:', chartDom);
      if (!chartDom) {
        console.error('未找到图表容器');
        return;
      }
      // 如果之前有实例，先销毁
      if (this.chart) {
        console.log('销毁之前的 ECharts 实例');
        this.chart.dispose();
      }
      // 初始化 ECharts 实例
      this.chart = echarts.init(chartDom);
      console.log('ECharts 实例:', this.chart);
      if (!this.chart) {
        console.error('ECharts 实例初始化失败');
        return;
      }
      // 可选：添加事件监听
      this.chart.on('mouseover', this.handleMouseOver);
    },
    // 获取图表数据并传递项目名
    fetchChartData(projectName) {
      getLineChartData({projectName}) // 将项目名称传递给后端
          .then((response) => {
            console.log('后端返回数据:', response);
            if (response.code === 200) {
              this.chartData = response.data; // 存储图表数据
              console.log('存储的图表数据:', this.chartData);
              this.updateChart(); // 更新图表
            } else {
              console.error("获取项目数据失败:", response.msg);
            }
          })
          .catch((error) => {
            console.error("获取图表数据失败:", error.response ? error.response.data : error.message);
          });
    },
    // 更新图表
    updateChart() {
      if (!this.chart) {
        console.error('ECharts 实例未初始化');
        return;
      }

      if (!this.chartData) {
        console.error('未能从后端数据中解析出 chartData 属性:', this.chartData);
        return;
      }

      const { contractAmount, outputValue, startDate, tasks, totalCost } = this.chartData;

      if (!startDate || !contractAmount || !outputValue || !totalCost || !tasks) {
        console.error('后端返回的数据不完整，无法渲染图表:', this.chartData);
        return;
      }

      const time = startDate;
      const contracts = contractAmount;
      const output = outputValue;
      const costs = totalCost;

      // 动态范围计算
      const maxDynamicValue = Math.max(...output, ...costs);
      const minDynamicValue = Math.min(...output, ...costs);
      const maxFixedValue = Math.max(...contracts);

      // 断点设置（跳过合同额与产值/成本间的空白）
      const breaks = [
        {
          startValue: Math.max(0, minDynamicValue), // 动态数据最大值以上开始
          endValue: Math.min(maxFixedValue, maxDynamicValue * 1.1), // 合同额以下结束
          interval: Math.ceil(maxDynamicValue / 5), // 动态生成刻度间隔
        },
      ];

      const option = {
        title: {
          text: `项目合同额、产值与成本变化折线图`,
          left: 'center', // 居中显示
          textStyle: {
            color: '#333',
            fontSize: 16,
            fontWeight: 'bold',
          },
        },
        color: ['#5470c6', '#91cc75', '#fac858'], // 自定义线条颜色
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(255, 255, 255, 0.7)', // 半透明背景
          borderColor: '#ccc',
          borderWidth: 1,
          textStyle: {
            color: '#333',
            fontSize: 12,
          },
          extraCssText: 'backdrop-filter: blur(10px); box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.1); border-radius: 8px; padding: 12px;',
          formatter: (params) => {
            const data = params[0].data; // 当前折线的数据点
            const contractAmount = data.contractAmount || '无';
            const totalCost = data.totalCost || '无';
            const outputValue = data.outputValue || '无';
            const taskDetail = this.tooltipData[data.index] || {}; // 获取对应的任务详情

            return `
          <div>
            <strong>日期：</strong>${params[0].axisValue}<br />
            <strong>合同额：</strong>${contractAmount}<br />
            <strong>成本：</strong>${totalCost}<br />
            <strong>产值：</strong>${outputValue}<br />
            <strong>任务名：</strong>${taskDetail.taskName || '无'}<br />
            <strong>人员：</strong>${taskDetail.memberName || '无'}<br />
            <strong>工时：</strong>${taskDetail.workHours || '无'}<br />
            <strong>月薪：</strong>${taskDetail.monthlySalary || '无'}
          </div>
        `;
          },
        },
        legend: {
          data: ['合同额', '产值', '成本'],
          left: '75%',
          textStyle: {
            fontSize: 12, // 调整文字大小
            color: '#333', // 调整文字颜色
          },
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true,
        },
        toolbox: {
          feature: {
            saveAsImage: { title: '导出为图片' },
          },
        },
        dataZoom: [
          {
            type: 'slider', // 滑动条
            start: 0, // 显示 0% ~ 100%
            end: 100,
          },
          {
            type: 'inside', // 鼠标滚动
            start: 0,
            end: 100,
          },
        ],
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: time, // x 轴时间数据
        },
        yAxis: {
          type: 'value',
          axisLine: { show: true, lineStyle: { color: '#333' } },
          axisLabel: { show: true, formatter: '{value}' },
          splitLine: { show: true, lineStyle: { type: 'dashed', color: '#ddd' } },
          min: Math.max(0, minDynamicValue * 0.9), // 最小值为动态区间的 90%
          max: maxFixedValue * 1.1, // 最大值为合同额的 110%
          axisBreaks: breaks, // 使用断点
        },
        series: [
          {
            name: '合同额',
            type: 'line',
            data: contracts.map((value, index) => ({
              value: value,
              contractAmount: value,
              outputValue: output[index],
              totalCost: costs[index],
              index,
            })),
          },
          {
            name: '产值',
            type: 'line',
            data: output.map((value, index) => ({
              value: value,
              contractAmount: contracts[index],
              outputValue: value,
              totalCost: costs[index],
              index,
            })),
          },
          {
            name: '成本',
            type: 'line',
            data: costs.map((value, index) => ({
              value: value,
              contractAmount: contracts[index],
              outputValue: output[index],
              totalCost: value,
              index,
            })),
          },
        ],
      };

      this.tooltipData = tasks.map((task, index) => ({
        taskName: task.taskName,
        memberName: task.memberName,
        workHours: task.workHours,
        monthlySalary: task.monthlySalary,
      }));

      try {
        this.chart.setOption(option);
        console.log('图表选项已设置');
      } catch (error) {
        console.error('设置图表选项时出错:', error.message);
      }
    },

    // 处理鼠标悬停事件，显示对应的任务信息
    handleMouseOver(event) {
      const dataIndex = event.dataIndex;
      const taskDetail = this.tooltipData[dataIndex] || {};
      this.tooltipData[dataIndex] = taskDetail;
    },

    sendTextMesg() {
      http.post('/api/tasks/notify')
          .then((response) => {
              this.$message.success("提醒短信已发送");
          })
          .catch((error) => {
            console.error(error);
            this.$message.error("提醒短信发送失败");
          });
    },
  },
  created() {
    this.fetchProjectsAndTask();
  },
  mounted(){
    // 不再在 mounted 中初始化图表
    // this.initChart(); 
  }
}
</script>

<style scoped>
.manager-task-container {
  padding: 20px;
}

.search-filter-section {
  background: #fff;
  padding: 20px;
  padding-top: 0;
  border-radius: 4px;
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.main-table-section {
  background: #fff;
  border-radius: 4px;
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

.new-task-row {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.new-task-item {
  margin-right: 10px;
  margin-bottom: 10px;
}

.el-tag {
  font-size: 14px;
  padding: 2px 10px;
}

#chart {
  width: 100%;
  height: 400px;
  background: #ffffff;
  border-radius: 10px;
  box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1);
  padding: 20px;
}
</style>
